//-------------------------------------------------------------
// \project pluginbusinesstraffic
// \file ModuleIceImportPoint.java
// \brief 导入点模块类
// \author 刘意琮
// \date 2016-11-8
// \attention
// Copyright(c) 超图软件股份有限公司 气象事业部
// All Rights Reserved
// \version 1.0
//-------------------------------------------------------------

package com.mg.pluginpamiss;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import com.mg.model.*;
import com.mg.objects.*;
import com.mg.pluginexample2.Model2;
import com.mg.pluginexample2.ModuleBase;

import java.awt.geom.Rectangle2D;
import java.awt.geom.Point2D;

public class ModuleImportPointFromTable extends ModuleBase
{
	public ModuleImportPointFromTable(int nID)
	{
		super(nID);
		
		m_alInputPort.add(new Port(this));
		m_alOutputPort.add(new Port(this, Port.Type.DatasetPoint));

		m_strDSOutput = "";
		m_strDatasetOutput = String.format("ImportPoint%d", m_nID);
    }

	public String GetGroupName()
	{
		return "CIMISS";
	}
	public String GetName()
	{
		return "导入点";
	}
	public String GetDescription()
	{
		return "";
	}
	
	public boolean OnAttach(Port portFrom, Port portTo)
	{
		try
		{
			int i = FindPort(portFrom, false);
			if (i != -1)
				return true;
			i = FindPort(portTo, true);
			if (i == -1)
				return false;
			if (portFrom.GetType() != portTo.GetType())
				return false;
			
			ArrayList<Param> alParam = new ArrayList<Param>();
			portFrom.GetModule().GetOutputParam(portFrom, alParam);
			if (alParam.size() != 1)
				return false;
			if (alParam.get(0).m_objValue != null && !(alParam.get(0).m_objValue instanceof List))
				return false;
			if (alParam.get(0).m_objValue instanceof List)
				m_map = (List<Map<String, String>>)alParam.get(0).m_objValue;
			
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
			return false;
		}
		return true;
	}
	
	//用于 参数->XML 等
	public int GetParam(ArrayList<Param> alParam)
	{
		try
		{
			super.GetParam(alParam);
			//-------------------------------------------------------------------------------------------------------------------
			Model2 model = ((Model2)m_model);

        	String strDatasources = model.GetWritableDatasources(false);
        	if (m_strDSOutput.isEmpty() && !strDatasources.isEmpty())
        		m_strDSOutput = strDatasources.split("\\|")[0];
        	//-------------------------------------------------------------------------------------------------------------------
        	String allColString="";
        	if (m_map!=null&&m_map.size()>1) {
        		Map<String, String> zd= m_map.get(0);
        		if (!m_longitudeString.isEmpty()||!m_longitudeString.equals("")) {
					;
				}
        		else if (zd.containsKey("x")) {
					m_longitudeString="x";
				}
        		else if (zd.containsKey("Lon")) {
        			m_latitudeString="Lon";
				}else  if (zd.containsKey("Longtitude")) {
					m_longitudeString="Longtitude";
				}else  if (zd.containsKey("longtitude")) {
					m_longitudeString="longtitude";
				}
				else  if (zd.containsKey("经度")) {
					m_longitudeString="经度";
				}
        		
        		if (!m_latitudeString.isEmpty()||!m_latitudeString.equals("")) {
					;
				}
        		else if (zd.containsKey("y")) {
        			m_latitudeString="y";
				}
        		else if (zd.containsKey("Lat")) {
        			m_latitudeString="Lat";
				}else  if (zd.containsKey("Latitude")) {
					m_latitudeString="Latitude";
				}else  if (zd.containsKey("latitude")) {
					m_latitudeString="latitude";
				}
				else  if (zd.containsKey("纬度")) {
					m_latitudeString="纬度";
				}
        		int keyCount=0;
        		Iterator it=zd.entrySet().iterator();
				while(it.hasNext())
				{
					Map.Entry entry = (Map.Entry)it.next();
					String Key=(String)entry.getKey();
					if(keyCount>0)
					{
						allColString+="|";
					}
					allColString+=Key;
					keyCount++;
				}
			}
        	//-------------------------------------------------------------------------------------------------------------------
        	alParam.add(new Param(Param.Datasource, m_longitudeString, "经度", "经度字段名称", "字段选择", Param.EditType.SelectOrInput, allColString));
        	alParam.add(new Param(Param.Datasource, m_latitudeString, "纬度", "纬度字段名称", "字段选择", Param.EditType.SelectOrInput, allColString));
			
        	alParam.add(new Param(Param.Datasource, m_strDSOutput, "数据源", "数据源别名", "输出端", Param.EditType.Select, strDatasources));
			alParam.add(new Param(Param.Dataset, m_strDatasetOutput, "数据集", "数据集名称", "输出端"));
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}		
		
		return alParam.size();
	}
	//用于 XML->参数 等
	public int SetParam(final ArrayList<Param> alParam)
	{
		int i = super.SetParam(alParam);
		try
		{
			m_longitudeString=(String)alParam.get(i++).m_objValue;
			m_latitudeString=(String)alParam.get(i++).m_objValue;
			m_strDSOutput = (String)alParam.get(i++).m_objValue;
			m_strDatasetOutput = (String)alParam.get(i++).m_objValue;
			
			m_alOutputPort.get(0).SetName(m_strDatasetOutput + "@" + m_strDSOutput);
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		return i;	
	}
	
	public boolean Execute()
	{
		try
		{
//			ArrayList<Param> alParam = new ArrayList<Param>();
//			Port port_inputPort= this.m_alInputPort.get(0).GetAttachedPipeList().get(0).GetIncomingPort();
//			
//			port_inputPort.GetModule().GetOutputParam(port_inputPort, alParam);
//			if (alParam.size() != 1)
//				return false;
//			if (alParam.get(0).m_objValue == null)
//				return false;
//			if (alParam.get(0).m_objValue instanceof List)
//				m_map = (List<Map<String, String>>)alParam.get(0).m_objValue;
//			else
//				return false;
			if (m_map!=null&&m_map.size()>0) {
				Model2 model = ((Model2)m_model);
				Workspace ws = model.m_ws;
				
				Datasource ds = ws.GetDatasource(m_strDSOutput);
				if (ds == null)
					return false;
				DatasetVector dv = ds.CreateDatasetVector("{\"Name\":\"" + m_strDatasetOutput + "\",\"Type\":\"Point\"}");
				dv.SetProjection("+proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs");
				Map<String, String> t_zd= m_map.get(0);
				Iterator it=t_zd.entrySet().iterator();
				while(it.hasNext()){
					Map.Entry entry = (Map.Entry)it.next();
					String Key=(String)entry.getKey();
					String keyTypeString="";
					
					Object param = null;
					try {
						float Value=Float.parseFloat(t_zd.get(Key));
						param=Value;
					} catch (Exception e) {
						param=t_zd.get(Key);
					}
					
					    if (param instanceof Float) {
						   keyTypeString="Single";
					   } 
					   else {
						   keyTypeString="TEXT";
					   }
					
					dv.AddField("{\"Name\":\""+Key+"\",\"Type\":\""+keyTypeString+"\",\"ForeignName\":\"\"}");
				}  
				//dv.AddField("{\"Name\":\"StationNum\",\"Type\":\"Text\",\"ForeignName\":\"\"}");
				//dv.AddField("{\"Name\":\"Value\",\"Type\":\"Single\",\"ForeignName\":\"\"}");
				
				Recordset rs = dv.Query(null, null);
		        Rectangle2D rcBounds = new Rectangle2D.Double(), rc;
		        
				for (int i=0;i<m_map.size();i++)
				{
					Map<String, String> zd= m_map.get(i);
					GeoPoint gp = new GeoPoint(Double.parseDouble(zd.get(m_longitudeString)), Double.parseDouble(zd.get(m_latitudeString)));
	                rc = gp.GetBounds();
	                if (rs.GetRecordCount() == 0)
	                    rcBounds = rc;
	                else
	                	Rectangle2D.union(rc, rcBounds, rcBounds);

	                rs.AddNew(gp);
	                for (String Key : t_zd.keySet()) {
	                	rs.SetFieldValue(Key, zd.get(Key));
	                }
//	                rs.SetFieldValue("StationNum", zd.get("站号"));
//	                rs.SetFieldValue("Value", zd.get(""));
	                rs.Update();
	                gp.Destroy();
				}
				rs.Destroy();
				
				dv.SetBounds(rcBounds);
				
				return true;
			}
			else {
				return false;
			}
		}
		catch (Exception ex)
		{
			ex.printStackTrace();
		}
		
		return false;
	}
	
	public int GetOutputParam(Port port, ArrayList<Param> alParam)
	{
		int i = FindPort(port, false);
		if (i == -1)
			return 0;
		alParam.add(new Param(Param.Datasource, m_strDSOutput));
		alParam.add(new Param(Param.Dataset, m_strDatasetOutput));
		return alParam.size();
	}

	List<Map<String, String>> m_map=null;
	
	String m_strDSOutput;
	String m_strDatasetOutput;
	String m_longitudeString="";
	String m_latitudeString="";
}
